﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.CheckManagement
{
   

    public partial class 检验单据 : DevExpress.XtraEditors.XtraForm
    {
        private static readonly HttpClient httpClient = new HttpClient();
        private int currentPage = 1;
        private int pageSize = 15;

        // 为不同状态创建不同的按钮RepositoryItem
        private RepositoryItemButtonEdit buttonEditForCheck;
        private RepositoryItemButtonEdit buttonEditForView;

        public 检验单据()
        {
            InitializeComponent();
            InitializeActionButtons(); // 初始化操作按钮
            if (httpClient.BaseAddress == null)
            {
                httpClient.BaseAddress = new Uri("http://localhost:5295");
            }

            // 绑定事件处理器
            this.Load += DocumentForm_Load;
            this.checkButton1.Click += QueryButton_Click;
            this.gridView1.CustomRowCellEdit += gridView1_CustomRowCellEdit; // 绑定自定义单元格编辑器事件
            //this.gridView1.CustomColumnDisplayText += gridView1_CustomColumnDisplayText;

            //this.isEnabled.Caption = "单据状态";
            //this.isEnabled.FieldName = "isEnabled";
            //this.isEnabled.ColumnEdit = null; // 取消CheckEdit
        }

        /// <summary>
        /// 初始化操作列的两种按钮样式
        /// </summary>
        private void InitializeActionButtons()
        {
            // 创建"检验"按钮
            buttonEditForCheck = new RepositoryItemButtonEdit();
            buttonEditForCheck.TextEditStyle = TextEditStyles.HideTextEditor;
            buttonEditForCheck.Buttons[0].Kind = ButtonPredefines.Glyph;
            buttonEditForCheck.Buttons[0].Caption = "检验";
            buttonEditForCheck.ButtonClick += ActionButton_ButtonClick; // 统一绑定点击事件
            gridControl1.RepositoryItems.Add(buttonEditForCheck);

            // 创建"查看"按钮
            buttonEditForView = new RepositoryItemButtonEdit();
            buttonEditForView.TextEditStyle = TextEditStyles.HideTextEditor;
            buttonEditForView.Buttons[0].Kind = ButtonPredefines.Glyph;
            buttonEditForView.Buttons[0].Caption = "查看";
            buttonEditForView.ButtonClick += ActionButton_ButtonClick; // 统一绑定点击事件
            gridControl1.RepositoryItems.Add(buttonEditForView);
        }

        /// <summary>
        /// 根据行数据动态分配操作按钮
        /// </summary>
        private void gridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            // 确保是操作列
            if (e.Column.FieldName == "colAction")
            {
                if (gridView1.GetRow(e.RowHandle) is DocumentDto rowData)
                {
                    // 根据 stateBool 的值来决定显示哪个按钮
                    // 假设 stateBool 为 true 表示"已完成/已检验"，显示"查看"
                    // 假设 stateBool 为 false 表示"未处理"，显示"检验"
                    e.RepositoryItem = rowData.isEnabled ? buttonEditForView : buttonEditForCheck;
                }
            }
        }

        /// <summary>
        /// 处理操作列按钮的点击事件
        /// </summary>
        private void ActionButton_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (gridView1.GetFocusedRow() is DocumentDto selectedRow)
            {
                // 根据按钮的标题来区分具体操作
                switch (e.Button.Caption)
                {
                    case "检验":
                        // 执行"检验"操作的逻辑
                        MessageBox.Show($"准备对检验单【{selectedRow.checkCode}】执行【检验】操作。",
                                        "操作确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 实例化质检录入窗体，传递当前行对象
                        TextDisplayForm form = new TextDisplayForm(selectedRow);
                        form.StartPosition = FormStartPosition.CenterParent; // 居中显示
                        form.ShowDialog(this); // 模态弹窗
                        break;

                    case "检验单据":
                        // 执行"查看"操作的逻辑
                        MessageBox.Show($"准备【检验单据】已完成的检验单【{selectedRow.checkCode}】。",
                                        "操作确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 在这里可以打开一个只读的详情界面

                        break;
                }
            }
        }

        /// <summary>
        /// 用于接收API返回的分页结果。
        /// 假设返回的JSON中包含一个名为 "items" 的列表。
        /// </summary>
        public class PageResult<T>
        {
            public List<T> items { get; set; }
            public int totalCount { get; set; }
            public int pageIndex { get; set; }
            public int pageSize { get; set; }
        }

        /// <summary>
        /// 用于接收单个检验单据的数据。
        /// 属性名使用camelCase是为了直接匹配GridColumn的FieldName，无需额外配置。
        /// </summary>
        public class DocumentDto
        {
            public string checkCode { get; set; }
            public string checkName { get; set; }
            public string checkWay { get; set; }
            public string productCategory { get; set; }
            public string checkVersion { get; set; }
            public string gProcessId { get; set; }

            public bool isEnabled { get; set; }
            public string gProcessName { get; set; }
            public int sampleCount { get; set; }
            public DateTime createTime { get; set; }
            public bool stateBool { get; set; }
            public string isEnabledText
            {
                get { return isEnabled ? "检验完毕" : "未检验"; }
            }
        }

        private async void DocumentForm_Load(object sender, EventArgs e)
        {
            await LoadDataAsync();
            
        }
        //private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        //{
        //    if (e.Column.FieldName == "isEnabled")
        //    {
        //        if (e.Value is bool b)
        //        {
        //            e.DisplayText = b ? "检验完毕" : "未检验";
        //        }
        //    }
        //}

        private async void QueryButton_Click(object sender, EventArgs e)
        {
            currentPage = 1; // 每次查询时重置到第一页
            await LoadDataAsync();
        }
    
        /// <summary>
        /// 从API异步加载数据并更新UI
        /// </summary>
        private async Task LoadDataAsync()
        {
            try
            {
                string checkCode = textEdit1.Text; // 获取检验单号
                string processName = textEdit2.Text; // 获取检验名称，作为ProcessName参数

                // 构建请求URL，包含分页和过滤参数
                var requestUri = $"/api/CheckStandard/GetAllCheck?PageIndex={currentPage}&PageSize={pageSize}&CheckCode={checkCode}&ProcessName={processName}";

                HttpResponseMessage response = await httpClient.GetAsync(requestUri);

                if (response.IsSuccessStatusCode)
                {
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<PageResult<DocumentDto>>(jsonResponse);

                    if (result != null && result.items != null)
                    {
                        // 将数据显示在表格上
                        gridControl1.DataSource = result.items;
                    }
                    else
                    {
                        gridControl1.DataSource = null;
                        MessageBox.Show("未查询到数据或返回的数据格式不正确。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    MessageBox.Show($"加载数据失败: {response.ReasonPhrase}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    gridControl1.DataSource = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"程序发生异常: {ex.Message}", "严重错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 检验单据_Load(object sender, EventArgs e)
        {

        }
    }
}